package br.ufpb.di.ppgi.util.security;

import java.util.Arrays;
import java.util.Collections;

public class GeradorDeSenha {
	public static final GeradorDeSenha ALPHA_NUMERICO =
		new GeradorDeSenha(
			CharRange.build('A', 'Z'),
			CharRange.build('0', '9'),
			CharRange.build('a', 'z')
		);
	
	public static final GeradorDeSenha ALPHA_NUMERICO_CAPS =
		new GeradorDeSenha(
			CharRange.build('A', 'Z'),
			CharRange.build('0', '9')
		);
	
	private final Character[] source;
	
	public GeradorDeSenha(char first, char last) {
		this(CharRange.build(first, last));
	}
	
	public GeradorDeSenha(CharRange ... ranges) {
		Character[] temp = new Character[0];
		for (CharRange range : ranges) {
			temp = generate(range.getFirst(), range.getLast(),temp);
		}
		source = temp;
	}
	
	private void shuffle() {
		Collections.shuffle(Arrays.asList(source));
	}
	
	private char[] toChar(int size) {
		char[] chars = new char[size];
		for (int i = 0; i< size; i++)
			chars[i] = source[i];
		return chars;
	}
	
	public String gerarSenha(int size) {
		shuffle();
		if (size > source.length)
			return new String(toChar(source.length)) + gerarSenha(size - source.length);
		else
			return new String(toChar(size));
	}
	
	private Character[] generate(char first, char last, Character[] chars) {
		if (chars == null) chars = new Character[0];
		int oldSize = chars.length;
		int newSize = oldSize + (last - first) + 1;
		chars = Arrays.copyOf(chars, newSize);
		for(int i = oldSize; i < newSize; i++)
			chars[i] = (char)(first + i - oldSize);
		return chars;
	}
}
